package WebGamble;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.awt.BorderLayout;
import javax.swing.JPanel;

public class PCEggsRecoder extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	static String BaseURL = "http://www.pceggs.com/play/pg28Insert.aspx?LID=";
	static Random rand = new Random();

	static private HttpResponse httpResponse;
	static private DefaultHttpClient httpClient = new DefaultHttpClient();
	static public class showImg extends JPanel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		JLabel jl = null;
		ImageIcon img = null;

		public showImg(InputStream bmpFile) throws IOException {
			img = new ImageIcon(ImageIO.read(bmpFile));
			jl = new JLabel(img);
			this.setLayout(new BorderLayout());
			this.add(jl, BorderLayout.CENTER);
		}
	}
	
	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException {
		HttpGet httpGet;
        httpGet = new HttpGet("http://www.pceggs.com/nologin.aspx");
		httpResponse = httpClient.execute(httpGet);
		String loginHtml = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
		httpGet.releaseConnection();
		
		httpGet = new HttpGet("http://www.pceggs.com/VerifyCode_Login.aspx?id=0." + Math.abs(rand.nextLong()));
        httpResponse = httpClient.execute(httpGet);
        JFrame pane = new JFrame("Image Pane");
        pane.getContentPane().add(new showImg(httpResponse.getEntity().getContent()));
        pane.pack();
        pane.setVisible(true);
        httpGet.releaseConnection();
        System.out.println("Please enter the verify code:");
        String VerifyCode;
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        VerifyCode = reader.readLine();
		
		Document loginDoc = Jsoup.parse(loginHtml);
		String loginURL = "http://www.pceggs.com/nologin.aspx";
		Elements loginInputs = loginDoc.select("input");
        HttpPost httpPost = new HttpPost(loginURL);
        List <NameValuePair> params = new ArrayList <NameValuePair>();
		for(Element input : loginInputs) {
			if(input.attr("type").compareToIgnoreCase("password") == 0) {
				input.attr("name", "txt_PWD");
				input.val("qazxcdews123321");
			}
			else if(input.attr("name").compareToIgnoreCase("email") == 0) {
				input.attr("name", "txt_UserName");
				input.val("365064421@qq.com");
			}
			else if(input.attr("name").compareToIgnoreCase("txt_VerifyCode") == 0) {
				input.val(VerifyCode);
			}
			else if(input.attr("name").compareToIgnoreCase("FromUrl") == 0) {
				input.val("http://www.pceggs.com/play/pc28.aspx");
			}
			else if(input.attr("name").compareToIgnoreCase("Login_Submit") == 0) {
				input.attr("name", "Login_Submit.x");
				input.val("32");
				params.add(new BasicNameValuePair(input.attr("name"), input.val()));
				System.out.println(input.attr("name") + ": " + input.val());
				input.attr("name", "Login_Submit.y");
				input.val("8");
				params.add(new BasicNameValuePair(input.attr("name"), input.val()));
				System.out.println(input.attr("name") + ": " + input.val());
				continue;
			}
			
			params.add(new BasicNameValuePair(input.attr("name"), input.val()));
			System.out.println(input.attr("name") + ": " + input.val());
		}
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        httpResponse = httpClient.execute(httpPost);
        if(httpResponse.getStatusLine().getStatusCode() == 302) {
        	System.out.println("Login success...");
        }
        loginHtml = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
        httpPost.releaseConnection();
        pane.dispose();
        
        while(true) {
        	FileWriter fw1 = new FileWriter("D:\\lab\\gamble\\OddsTrain1.log", true);
            FileWriter fw2 = new FileWriter("D:\\lab\\gamble\\OddsTest1.log", true);
        	
            httpGet = new HttpGet("http://www.pceggs.com/play/pc28.aspx");
            httpResponse = httpClient.execute(httpGet);
            String html = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");

            //httpGet.releaseConnection();
            Document document = Jsoup.parse(html);
            Elements elements = document.select("#panel tr:eq(5) td:eq(0)");
            int gambleId = Integer.parseInt(elements.get(0).text());
            elements = document.select("#panel tr:eq(5) td:eq(5) script");
            int lid = Integer.parseInt(elements.get(0).html().substring(12, 18));
            String gambleURL = BaseURL + lid;
            int i;
            double[] oddsList = new double[28];
            String odds;
        	
        	httpGet = new HttpGet("http://www.pceggs.com/play/pc28.aspx");
            httpResponse = httpClient.execute(httpGet);
            html = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
            httpGet.releaseConnection();
            document = Jsoup.parse(html);
            elements = document.select(".infro span:eq(3)");
            
            Pattern p = Pattern.compile("GetRTime\\([0-9]+\\);"), p1 = Pattern.compile("[0-9]+");
            Matcher m = p.matcher(html);
            m.find();
            html = m.group();
            m = p1.matcher(html);
            m.find();
            int timeout = Integer.parseInt(m.group());
            if(timeout <= 2) {
            	System.out.println("Timeout...");
            	Thread.sleep(5000);
            	continue;
            }
            
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Thread.currentThread();
    		Thread.sleep((timeout - 2) * 1000);

            httpGet = new HttpGet("http://www.pceggs.com/play/pg28mode.aspx?refresh=" + (lid));
            fw1.write((lid) + " ");
            httpGet.addHeader("X_REQUESTED_WITH", "XMLHttpRequest");
            httpGet.addHeader("Referer", gambleURL);
            httpResponse = httpClient.execute(httpGet);
            odds = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
            i = 0;
            for(String value : odds.split(",")) {
            	oddsList[i] = Double.parseDouble(value);
            	System.out.print(oddsList[i] + ", ");
            	fw1.write(oddsList[i] + " ");
            	i++;
            }
            httpGet.releaseConnection();
            
            System.out.println();
            fw1.write("\n");

            Thread.sleep(50000);
            
            httpGet = new HttpGet("http://www.pceggs.com/play/pc28.aspx");
            httpResponse = httpClient.execute(httpGet);
            html = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");

            //httpGet.releaseConnection();
            document = Jsoup.parse(html);
            elements = document.select("#panel tr:eq(5) td:eq(0)");
            gambleId = Integer.parseInt(elements.get(0).text());
            elements = document.select("#panel tr:eq(5) td:eq(5) script");
            lid = Integer.parseInt(elements.get(0).html().substring(12, 18));
            gambleURL = BaseURL + lid;
        	
        	httpGet = new HttpGet("http://www.pceggs.com/play/pc28.aspx");
            httpResponse = httpClient.execute(httpGet);
            html = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
            httpGet.releaseConnection();
            document = Jsoup.parse(html);
            elements = document.select(".infro span:eq(3)");
            
            p = Pattern.compile("GetRTime\\([0-9]+\\);"); p1 = Pattern.compile("[0-9]+");
            m = p.matcher(html);
            m.find();
            html = m.group();
            m = p1.matcher(html);
            m.find();
            
          elements = document.select("#panel tr:gt(5) script");
          int[] history = new int[3];
          for(i = 0; i < history.length; i++) {
          	history[i] = Integer.parseInt(elements.get(i * 4).html().substring(26, 28)) - 10;
          }
            
            df = new SimpleDateFormat("yyyy-MM-dd HH:mm");


            httpGet = new HttpGet("http://www.pceggs.com/play/pg28mode.aspx?refresh=" + (lid - 1));
            fw2.write((lid - 1) + " ");
            httpGet.addHeader("X_REQUESTED_WITH", "XMLHttpRequest");
            httpGet.addHeader("Referer", gambleURL);
            httpResponse = httpClient.execute(httpGet);
            odds = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
            i = 0;
            for(String value : odds.split(",")) {
            	oddsList[i] = Double.parseDouble(value);
            	System.out.print(oddsList[i] + ", ");
            	fw2.write(oddsList[i] + " ");
            	i++;
            }
            httpGet.releaseConnection();
            
            fw2.write(history[0] + " ");
            
            System.out.println();
            fw2.write("\n");
            
            fw1.close();
            fw2.close();
        }
        
	}
}
